import Taro, { getEnv } from '@tarojs/taro'
import { localStg } from '@/utils';

/**
 * H5环境下使用原生fetch API上传文件
 * @param filePath 文件路径
 * @param uploadUrl 上传地址
 * @returns Promise<UploadResult>
 */
async function uploadWithFetch(filePath: string, uploadUrl: string): Promise<UploadResult> {
  try {
    console.log('使用fetch API上传图片:', filePath, uploadUrl)
    
    // 获取token
    const token = localStg.get('token')
    console.log('fetch上传使用的token:', token)
    
    // 将文件路径转换为File对象
    const response = await fetch(filePath)
    const blob = await response.blob()
    const file = new File([blob], Date.now() + '.jpg', { type: 'image/jpeg' })
    
    const formData = new FormData()
    formData.append('file', file)
    
    const headers: HeadersInit = {}
    if (token) {
      headers['X-Access-Token'] = token
    }
    
    const fetchResponse = await fetch(uploadUrl, {
      method: 'POST',
      body: formData,
      headers,
    })
    
    console.log('fetch上传响应状态:', fetchResponse.status)
    
    if (fetchResponse.ok) {
      const responseData = await fetchResponse.text()
      console.log('fetch上传返回数据:', responseData)
      
      try {
        // 尝试解析为JSON
        const response = JSON.parse(responseData)
        console.log('fetch解析后的响应:', response)
        
        // 处理各种可能的响应格式
        if (response.success === true && response.message) {
          return {
            success: true,
            url: response.message
          }
        } else if (response.code === 200 && response.data) {
          return {
            success: true,
            url: response.data.url || response.data
          }
        } else {
          return {
            success: true,
            url: responseData
          }
        }
      } catch (parseError) {
        // 如果解析JSON失败，直接使用原始数据作为URL
        console.log('fetch JSON解析失败，直接使用原始数据:', responseData)
        return {
          success: true,
          url: responseData
        }
      }
    } else {
      console.error('fetch上传失败，状态码:', fetchResponse.status)
      return {
        success: false,
        error: `HTTP ${fetchResponse.status}: 上传失败`
      }
    }
  } catch (error) {
    console.error('fetch上传异常:', error)
    throw error // 抛出错误让外层捕获
  }
}

export interface UploadResult {
  success: boolean
  url?: string
  error?: string
}

export interface ImageUploadOptions {
  maxCount?: number
  sizeType?: ('original' | 'compressed')[]
  sourceType?: ('album' | 'camera')[]
}

/**
 * 选择并上传图片
 * @param options 上传选项
 * @returns Promise<UploadResult[]>
 */
export async function selectAndUploadImages(options: ImageUploadOptions = {}): Promise<UploadResult[]> {
  const {
    maxCount = 9,
    sizeType = ['original', 'compressed'],
    sourceType = ['album', 'camera']
  } = options

  try {
    // 选择图片
    const chooseResult = await Taro.chooseImage({
      count: maxCount,
      sizeType,
      sourceType
    })

    if (!chooseResult.tempFilePaths || chooseResult.tempFilePaths.length === 0) {
      return []
    }

    // 显示上传进度
    Taro.showLoading({
      title: '上传中...',
      mask: true
    })

    // 并发上传所有图片，如果主要方法失败则尝试备用方法
    const uploadPromises = chooseResult.tempFilePaths.map(async (filePath) => {
      const result = await uploadSingleImage(filePath)
      // 如果主要方法失败，尝试备用方法
      if (!result.success) {
        console.log('主要方法失败，尝试备用方法')
        return await uploadImageAlternative(filePath)
      }
      return result
    })
    const results = await Promise.all(uploadPromises)

    Taro.hideLoading()

    // 统计结果
    const successCount = results.filter(r => r.success).length
    const failCount = results.filter(r => !r.success).length

    if (successCount > 0) {
      Taro.showToast({
        title: `成功上传${successCount}张图片`,
        icon: 'success',
        duration: 2000
      })
    }

    if (failCount > 0) {
      Taro.showToast({
        title: `${failCount}张图片上传失败`,
        icon: 'error',
        duration: 2000
      })
    }

    return results

  } catch (error) {
    Taro.hideLoading()
    console.error('选择图片失败:', error)
    Taro.showToast({
      title: '选择图片失败',
      icon: 'error',
      duration: 2000
    })
    return []
  }
}

/**
 * 上传单张图片
 * @param filePath 图片路径
 * @returns Promise<UploadResult>
 */
async function uploadSingleImage(filePath: string): Promise<UploadResult> {
  try {
    console.log('开始上传图片:', filePath, "😂")
    
    // H5环境下使用相对路径，避免跨域和端口问题
    const isH5 = getEnv() === 'WEB'
    const uploadUrl = isH5 
      ? '/api/file-service/FileUpload/custom_saveImage'
      : 'https://anfine.huasun-healthcare.com:80/file-service/FileUpload/custom_saveImage'
    
    // H5环境下使用原生fetch API作为备选方案
    if (isH5) {
      try {
        return await uploadWithFetch(filePath, uploadUrl)
      } catch (fetchError) {
        console.log('fetch上传失败，尝试Taro.uploadFile:', fetchError)
      }
    }
    
    // 获取token
    const token = localStg.get('token')
    console.log('Taro上传使用的token:', token)
    
    const uploadResult = await Taro.uploadFile({
      // url: 'http://192.168.10.87:8082/file-service/FileUpload/custom_saveImage',
      url: uploadUrl, // 替换为你的后端接口地址
      filePath: filePath,
      fileName: Date.now() + '.jpg', 
      name: 'file', // 后端接收文件的字段名
      formData: {
        // type: 'image'
      },
      header: {
        'content-type': 'multipart/form-data',
        ...(token ? { 'X-Access-Token': token } : {})
      },
    })

    console.log('上传结果:', uploadResult)
    console.log('状态码:', uploadResult.statusCode)
    console.log('返回数据:', uploadResult.data)

    if (uploadResult.statusCode === 200) {
      try {
        // 尝试解析为JSON
        const response = JSON.parse(uploadResult.data)
        console.log('解析后的响应:', response)
        
        // 处理各种可能的响应格式
        if (response.success === true && response.message) {
          // 格式: { success: true, message: "url" }
          return {
            success: true,
            url: response.message
          }
        } else if (response.code === 200 && response.data) {
          // 格式: { code: 200, data: "url" }
          return {
            success: true,
            url: response.data.url || response.data
          }
        } else if (response.message && !response.success) {
          return {
            success: false,
            error: response.message || '服务器返回错误'
          }
        } else {
          return {
            success: false,
            error: response.message || '服务器返回错误'
          }
        }
      } catch (parseError) {
        // 如果解析JSON失败，检查是否直接返回了URL字符串
        console.log('JSON解析失败，检查是否为直接URL:', uploadResult.data)
        
        if (typeof uploadResult.data === 'string') {
          // 检查是否是URL
          if (uploadResult.data.startsWith('http')) {
            console.log('检测到直接返回的URL:', uploadResult.data)
            return {
              success: true,
              url: uploadResult.data
            }
          }
          // 尝试作为URL使用
          return {
            success: true,
            url: uploadResult.data
          }
        }
        
        console.error('解析响应失败:', parseError)
        return {
          success: false,
          error: '服务器响应格式错误'
        }
      }
    } else {
      console.error('上传失败，状态码:', uploadResult.statusCode)
      return {
        success: false,
        error: `HTTP ${uploadResult.statusCode}: ${uploadResult.data || '上传失败'}`
      }
    }
  } catch (error) {
    console.error('上传图片异常:', error)
    console.error('错误详情:', {
      error: error,
      errorType: typeof error,
      errorMessage: error instanceof Error ? error.message : String(error),
      taroEnv: getEnv(),
      uploadUrl: isH5 
        ? '/api/file-service/FileUpload/custom_saveImage'
        : 'https://anfine.huasun-healthcare.com:80/file-service/FileUpload/custom_saveImage'
    })
    return {
      success: false,
      error: error instanceof Error ? error.message : '上传失败'
    }
  }
}

/**
 * 选择单张图片并上传
 * @param options 上传选项
 * @returns Promise<UploadResult | null>
 */
export async function selectAndUploadSingleImage(options: Omit<ImageUploadOptions, 'maxCount'> = {}): Promise<UploadResult | null> {
  try {
    const chooseResult = await Taro.chooseImage({
      count: 1,
      sizeType: options.sizeType || ['original', 'compressed'],
      sourceType: options.sourceType || ['album', 'camera']
    })

    if (!chooseResult.tempFilePaths || chooseResult.tempFilePaths.length === 0) {
      return null
    }

    Taro.showLoading({
      title: '上传中...',
      mask: true
    })

    // 先尝试主要方法
    let result = await uploadSingleImage(chooseResult.tempFilePaths[0])
    
    // 如果主要方法失败，尝试备用方法
    if (!result.success) {
      console.log('单张图片主要方法失败，尝试备用方法')
      result = await uploadImageAlternative(chooseResult.tempFilePaths[0])
    }

    Taro.hideLoading()

    if (result.success) {
      Taro.showToast({
        title: '上传成功',
        icon: 'success',
        duration: 2000
      })
    } else {
      Taro.showToast({
        title: result.error || '上传失败',
        icon: 'error',
        duration: 2000
      })
    }

    return result

  } catch (error) {
    Taro.hideLoading()
    console.error('选择单张图片失败:', error)
    Taro.showToast({
      title: '选择图片失败',
      icon: 'error',
      duration: 2000
    })
    return null
  }
}

/**
 * 备用上传方法 - 使用不同的参数组合
 * @param filePath 图片路径
 * @returns Promise<UploadResult>
 */
export async function uploadImageAlternative(filePath: string): Promise<UploadResult> {
  try {
    console.log('使用备用方法上传图片:', filePath)
    
    // H5环境下使用相对路径，避免跨域和端口问题
    const isH5 = getEnv() === 'WEB'
    const uploadUrl = isH5 
      ? '/api/file-service/FileUpload/custom_saveImage'
      : 'https://anfine.huasun-healthcare.com:80/file-service/FileUpload/custom_saveImage'
    
    // H5环境下使用原生fetch API作为备选方案
    if (isH5) {
      try {
        return await uploadWithFetch(filePath, uploadUrl)
      } catch (fetchError) {
        console.log('备用方法fetch上传失败，尝试Taro.uploadFile:', fetchError)
      }
    }
    
    // 获取token
    const token = localStg.get('token')
    console.log('备用方法Taro上传使用的token:', token)
    
    // 参考 index.vue 的简单写法
    const uploadResult = await Taro.uploadFile({
      url: uploadUrl,
      // url: 'http://192.168.10.87:8082/file-service/FileUpload/custom_saveImage',
      filePath: filePath,
      fileName: Date.now() + '.jpg', 
      name: 'file',
      formData: {},
      header: {
        'content-type': 'multipart/form-data',
        ...(token ? { 'X-Access-Token': token } : {})
      },
    })

    console.log('备用方法上传结果:', uploadResult)
    console.log('备用方法状态码:', uploadResult.statusCode)
    console.log('备用方法返回数据:', uploadResult.data)

    if (uploadResult.statusCode === 200) {
      try {
        // 尝试解析为JSON
        const response = JSON.parse(uploadResult.data)
        console.log('备用方法解析后的响应:', response)
        
        // 处理各种可能的响应格式
        if (response.success === true && response.message) {
          // 格式: { success: true, message: "url" }
          return {
            success: true,
            url: response.message
          }
        } else if (response.code === 200 && response.data) {
          // 格式: { code: 200, data: "url" }
          return {
            success: true,
            url: response.data.url || response.data
          }
        } else if (response.message && !response.success) {
          return {
            success: false,
            error: response.message || '服务器返回错误'
          }
        } else {
          // 尝试直接使用 data 字段
          return {
            success: true,
            url: uploadResult.data
          }
        }
      } catch (parseError) {
        // 如果解析JSON失败，直接使用原始数据作为URL
        console.log('备用方法JSON解析失败，直接使用原始数据:', uploadResult.data)
        return {
          success: true,
          url: uploadResult.data
        }
      }
    } else {
      console.error('备用方法上传失败，状态码:', uploadResult.statusCode)
      return {
        success: false,
        error: `HTTP ${uploadResult.statusCode}: ${uploadResult.data || '上传失败'}`
      }
    }
  } catch (error) {
    console.error('备用方法上传图片异常:', error)
    return {
      success: false,
      error: error instanceof Error ? error.message : '上传失败'
    }
  }
}

/**
 * 预览图片
 * @param urls 图片URL数组
 * @param current 当前显示的图片索引
 */
export function previewImages(urls: string[], current: number = 0) {
  Taro.previewImage({
    urls,
    current: urls[current] || urls[0]
  })
}

/**
 * 删除图片确认
 * @param onConfirm 确认删除回调
 */
export function confirmDeleteImage(onConfirm: () => void) {
  Taro.showModal({
    title: '确认删除',
    content: '确定要删除这张图片吗？',
    success: (res) => {
      if (res.confirm) {
        onConfirm()
      }
    }
  })
}

/**
 * 测试上传功能 - 用于调试
 */
export async function testUpload() {
  try {
    const chooseResult = await Taro.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album']
    })

    if (!chooseResult.tempFilePaths || chooseResult.tempFilePaths.length === 0) {
      return
    }

    console.log('测试上传 - 选择的图片路径:', chooseResult.tempFilePaths[0])
    
    Taro.showLoading({
      title: '测试上传中...',
      mask: true
    })

    // 测试主要方法
    console.log('测试主要上传方法...')
    const mainResult = await uploadSingleImage(chooseResult.tempFilePaths[0])
    console.log('主要方法结果:', mainResult)

    if (!mainResult.success) {
      console.log('主要方法失败，测试备用方法...')
      const altResult = await uploadImageAlternative(chooseResult.tempFilePaths[0])
      console.log('备用方法结果:', altResult)
    }

    Taro.hideLoading()
    
    Taro.showModal({
      title: '测试完成',
      content: '请查看控制台日志了解详细结果',
      showCancel: false
    })

  } catch (error) {
    Taro.hideLoading()
    console.error('测试上传失败:', error)
    Taro.showToast({
      title: '测试失败',
      icon: 'error'
    })
  }
}
